package com.example.zuul.web;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AccessFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String accessToken = request.getParameter("accessToken");

        if(accessToken==null){
            System.out.println("access token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody("{\"result\":\"accessToken is empty!\"}");

            String remoteHost = request.getRemoteHost();
            System.out.println("ip="+remoteHost);
            String encode = DigestUtils.md5DigestAsHex(remoteHost.getBytes());
            System.out.println("encode="+encode);
            Cookie cookie = new Cookie("accessToken", encode);
            HttpServletResponse response = ctx.getResponse();
            response.addCookie(cookie);
            return null;
        }else{
            String remoteHost = request.getRemoteHost();
            System.out.println("ip="+remoteHost);
            String encode = DigestUtils.md5DigestAsHex(remoteHost.getBytes());
            System.out.println("encode"+encode);

            if(accessToken.equals(encode)==false){
                System.out.println("access token is error");

                ctx.setSendZuulResponse(false);
                ctx.setResponseStatusCode(401);
                ctx.setResponseBody("{\"result\":\"accessToken is empty!\"}");
            }
        }

        return null;
    }
}
